<?php

namespace User\Controller;

use Zend\Form\Form;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Stdlib\Parameters;

use Zend\View\Model\ViewModel;
use User\Service\User as UserService;
use User\Options\UserControllerOptionsInterface;

class UserController extends AbstractActionController
{
    const ROUTE_REGISTER = "user/register";
    const CONTROLLER_NAME = "user";
    const ROUTE_LOGIN = "user/login";
    public function indexAction()
    {
        return new ViewModel();
    }

    public function authenticateAction()
    {
        if ($this->UserAuthentication()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
        else{
            var_dump($this->UserAuthentication()->getIdentity());
        }

        $adapter = $this->UserAuthentication()->getAuthAdapter();
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));

        $result = $adapter->prepareForAuthentication($this->getRequest());

        // Return early if an adapter returned a response
        if ($result instanceof Response)
        {
            return $result;
        }

        $auth =  $this->UserAuthentication()->getAuthService()->authenticate($adapter);

        //var_dump($this->UserAuthentication()->getAuthService());
        if(!$auth->isValid())
        {
            var_dump('login not success');
            var_dump($auth->getIdentity());
            //return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN) . ($redirect ? '?redirect='. rawurlencode($redirect) : ''));
        }
        else
        {
            var_dump('login success');
            var_dump($auth->getIdentity());
           // var_dump($this->UserAuthentication());
        }

        var_dump($this->UserAuthentication()->getIdentity());

        /*
        $route = $this->getOptions()->getLoginRedirectRoute();

        if (is_callable($route)) {
            $route = $route($this->UserAuthentication()->getIdentity());
        }

        return $this->redirect()->toRoute($route);*/
    }

    public function loginAction()
    {
        if($this->UserAuthentication()->hasIdentity())
        {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
        $form = $this->getLoginForm();
        $request = $this->getRequest();
        $post = $request->getPost();

        /*
        if ($this->getOptions()->getUseRedirectParameterIfPresent())
        {
           // $redirect = $request->getQuery()->get('redirect', (!empty($post['redirect'])) ? $post['redirect'] : false);
        } else {
            //$redirect = false;
        }*/

        if(!$request->isPost()) {
            return array(
                'form' => $form,
                //'redirect'  => $redirect,
                //'enableRegistration' => $this->getOptions()->getEnableRegistration(),
            );
        }

        $form->setData($post);

        if($form->isValid())
        {
            $this->UserAuthentication()->getAuthAdapter()->resetAdapters();
            $this->UserAuthentication()->getAuthService()->clearIdentity();
            //var_dump('ok');
        }
        return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));

    }


    public function logoutAction()
    {
        $this->UserAuthentication()->getAuthAdapter()->resetAdapters();
        $this->UserAuthentication()->getAuthAdapter()->logoutAdapters();
        $this->UserAuthentication()->getAuthService()->clearIdentity();
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));
        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
            return $this->redirect()->toRoute($redirect);
        }

        return $this->redirect()->toRoute($this->getOptions()->getLogoutRedirectRoute());
    }

    public function registerAction()
    {
        if($this->UserAuthentication()->hasIdentity())
        {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }

        $form = $this->getRegisterForm();
        $service = $this->getUserService();
        $request = $this->getRequest();
        
        if($request->getPost()->get('redirect'))
        {
            $redirect = $request->getQuery()->get('redirect');
        }
        else
        {
            $redirect = false;
        }
        
        $redirectUrl = $this->url()->fromRoute(static::ROUTE_REGISTER) . ($redirect ? '?redirect=' . rawurlencode($redirect) : '');
	
        $prg = $this->prg($redirectUrl , true);
        
        if($prg instanceof Response)
        {
            return $prg;
        }
        elseif($prg === false)
        {
            return new ViewModel( array(
                'form' => $form ,
                //'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            ));
        }
        
        $post = $prg;
        $user = $service->register((array)$post);
        $redirect = isset($prg['redirect']) ? $prg['redirect'] : null;

        if(!$user)
        {
            return new ViewModel( array(
                'form' => $form ,
                //'enableRegistration' => $this->getOptions()->getEnableRegistration(),
                'redirect' => $redirect,
            ));
        }

        if($service->getOptions()->getLoginAfterRegistration())
        {
            $identityFields = $service->getOptions()->getAuthIdentityFields();
            if(in_array('email' , $identityFields))
            {
                $post['identity'] = $user->getEmail();
            }
            elseif (in_array('username', $identityFields))
            {
                $post['identity'] = $user->getUsername();
            }
            $post['credential'] = $post['password'];
            $request->setPost(new Parameters($post));
            return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));
        }
        return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN) . ($redirect ? '?redirect='. rawurlencode($redirect) : ''));
    }
    
    protected $userService;
    public function getUserService()
    {
        if(!$this->userService)
        {
            $this->userService = $this->getServiceLocator()->get('user_service');
        }
        return $this->userService;
    }
            
    protected $registerForm;
    
    public function getRegisterForm(){
        if(!$this->registerForm)
        {
            $this->registerForm = $this->getServiceLocator()->get('user_register_form');
        }
        return $this->registerForm;
    }
    
    public function setRegisterForm($registerForm)
    {
        $this->registerForm = $registerForm;
    }

    protected $loginForm;
    public function getLoginForm()
    {
        if(!$this->loginForm)
        {
            $this->setLoginForm($this->getServiceLocator()->get('user_login_form'));
        }
        return $this->loginForm;
    }

    public function setLoginForm(Form $loginForm)
    {
        $this->loginForm = $loginForm;
        return $this;
    }


    protected $options;
    public function getOptions()
    {
        if(!$this->options instanceof UserControllerOptionsInterface)
        {
            $this->setOptions($this->getServiceLocator()->get('user_module_options'));
        }
        return $this->options;
    }
    
    public function setOptions(UserControllerOptionsInterface $options)
    {
        $this->options = $options;
    }
}
